package com.iyouqu.dsp.api.server;

import java.util.Collection;

import javax.annotation.PreDestroy;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;

@Component
public class NettyServer {

	@Autowired
	ApplicationContext ac;
	
	@Value("#{configProperties['server.host']}")
	private String host;
	
	@Value("#{configProperties['server.rootResourcePath']}")
	private String rootResourcePath;
	
	@Value("#{configProperties['server.port']}")
	private int port;
	
	@Value("#{configProperties['server.executorThreadCount']}")
	private int executorThreadCount;
	

	private NettyJaxrsServer nettyServer;

	public void start() {
		

		Collection<Object> providers = ac.getBeansWithAnnotation(Provider.class).values();
		Collection<Object> controllers = ac.getBeansWithAnnotation(Controller.class).values();

		Assert.notEmpty(controllers);

		//Resteasy 
		ResteasyDeployment deployment = new ResteasyDeployment();
		
		// 增加过滤器 和 JSON providers
		if (providers != null) {
			deployment.getProviders().addAll(providers);
		}
		
		// 增加restful API
		deployment.getResources().addAll(controllers);

		// nettyServer
		nettyServer = new NettyJaxrsServer();
		nettyServer.setDeployment(deployment);
		nettyServer.setHostname(host);
		nettyServer.setPort(port);
		nettyServer.setRootResourcePath(rootResourcePath);
		nettyServer.setSecurityDomain(null);
		nettyServer.setExecutorThreadCount(executorThreadCount);
		nettyServer.start();
		
		System.out.println("netty server start at "+port);
	}

	@PreDestroy
	public void cleanUp() {
		nettyServer.stop();
	}

}
